package com.unis.iptv.common.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DownloadPicture {
	private static Log iptvCourse = LogFactory.getLog("iptvCourse");
	
	public static void main(String[] args) {
		download(
				"http://10.255.128.8:8080/iptvepg/images/poster/20121116002730.jpg",
				"/Users/LYBeta/System/log/iptv_data_device/course_Lossssg/");
	}
	
	public static void download(String reqUrl, String savePath) {
		
		HttpURLConnection url_con = null;
		try {
			File file = new File(savePath.substring(0,
					savePath.lastIndexOf("/")));
			if (!file.exists()) {
				file.mkdirs();
			}
			URL url = new URL(reqUrl);
			url_con = (HttpURLConnection) url.openConnection();
			url_con.setRequestMethod("POST");
			url_con.setDoOutput(true);
			url_con.getOutputStream().flush();
			url_con.getOutputStream().close();
			
			InputStream is = url_con.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is,
					"gbk"));
			FileOutputStream fw = null;
			iptvCourse.info("图片下载地址util===========" + reqUrl);
			iptvCourse.info("savePath======> " + savePath);
			File f = new File(savePath.substring(0, savePath.lastIndexOf("/"))
					+ "ss.jpg");
			if (!f.exists()) {
				f.mkdirs();
			}
			fw = new FileOutputStream(savePath, true);
			int num = -1;
			while ((num = is.read()) != (-1))// 是否读完所有数据
			{
				fw.write(num);// 将数据写往文件
			}
			rd.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (url_con != null) {
				url_con.disconnect();
			}
		}
	}
	
}
